
import mysql = require("mysql2")
import { Logger } from "./Logger";
import fs = require("fs")
import path = require("path")


export class MySqlUtil {

    private static MySql_Host: string = ""; //
    private static MySql_Port: number = 3306; //
    private static MySql_User: string = ""
    private static MySql_Pass: string = "";

    private static connection: any;
    private static isConnected: boolean;

    private static initConfig(configPath: string = path.resolve() + "/config/mysql.json") {
        let data: Buffer = fs.readFileSync(configPath);
        let obj: Object = JSON.parse(data.toString());
        this.MySql_Host = obj["host"];
        this.MySql_Port = obj["port"]
        this.MySql_User = obj["user"];
        this.MySql_Pass = obj["pass"]
    }

    public static async init() {
        this.initConfig()
        let config: object = {
            "host": this.MySql_Host,
            "port": this.MySql_Port,
            "user": this.MySql_User,
            "password": this.MySql_Pass,
        };
        this.connection = mysql.createConnection(config);
        Logger.log("MySqlUtil.init", config, this.connection)
        this.connection.on("connect", (err) => {
            if (!err) {
                this.isConnected = true;
                Logger.log("MySqlUtil.onConnect==", err)
            } else {
                Logger.log("MySqlUtil.onConnect=error=", err)
            }
        })
        this.connection.on("error", (err) => {
            this.isConnected = false;
            Logger.log("MySqlUtil.onError==", err)
        })
        this.connection.on("end", (err) => {
            // this.isConnected = false;
            Logger.log("MySqlUtil.end==", err)
        })

        await this.connect();

        // this.connection.end();
        this.connection.query("show database;", (err, result) => {
            if (err) {
                Logger.error('[database eror] - ', err.message);
                return;
            }
            Logger.log("database resp=", result);
        });
        // let test:string = "SELECT * FROM users;";
        // let test:string = "INSERT INTO users values(null, 100003, 'test3', 'nickname3');";
        // this.executeSql(test);
    }

    public static connect() {
        return new Promise((resolve, reject) => {
            if (!this.isConnected) {
                this.connection.connect((err) => {
                    if (err) {
                        Logger.error('MySqlUtil connect error:', err);
                        return;
                    }
                    Logger.log('[MySqlUtil connect]  succeed!');
                    resolve(null);
                });
            }else{
                resolve(null);
            }
        })
    }

    public static select(sql: string, callback: Function = null) {
        // let  sql = 'SELECT * FROM websites';
        //查
        this.init();
        this.connection.query(sql, (err, result) => {
            if (err) {
                Logger.error('[SELECT ERROR] - ', err.message);
                if (callback) {
                    callback(err)
                }
                return;
            }
            // Logger.log("select resp=", result);
            if (callback) {
                callback(err, result)
            }
        });
    }

    public static insert(sql: string, addSqlParams: Array<any>, callback: Function = null) {
        // var  addSql = 'INSERT INTO websites(Id,name,url,alexa,country) VALUES(0,?,?,?,?)';
        // var  addSqlParams = ['菜鸟工具', 'https://c.runoob.com','23453', 'CN'];
        // REPLACE INTO table (id, name, user, passwd) VALUES (1, '极客点儿', 'admin', 'abcdef');
        this.init();
        //增
        this.connection.query(sql, addSqlParams, (err, result) => {
            if (err) {
                Logger.error('[INSERT ERROR] - ', err.message);
                if (callback) {
                    callback(err)
                }
                return;
            }
            Logger.log("INSERT resp=", result);
            if (callback) {
                callback(err, result)
            }
        });
    }

    public static update(modSql: string, modSqlParams: Array<any>, callback: Function = null) {
        // REPLACE INTO table (id, name, user, passwd) VALUES (1, '极客点儿', 'admin', 'abcdef');
        // var modSql = 'UPDATE websites SET name = ?,url = ? WHERE Id = ?';
        // var modSqlParams = ['菜鸟移动站', 'https://m.runoob.com', 6];
        this.init();
        //改
        this.connection.query(modSql, modSqlParams, (err, result) => {
            if (err) {
                Logger.error('[UPDATE ERROR] - ', err.message);
                if (callback) {
                    callback(err)
                }
                return;
            }
            Logger.log("UPDATE resp=", result);
            if (callback) {
                callback(err, result)
            }
        });
    }

    public static delete(delSql: string, callback: Function) {
        // var delSql = 'DELETE FROM websites where id=6';
        this.init();
        //删
        this.connection.query(delSql, (err, result) => {
            if (err) {
                Logger.error('[DELETE ERROR] - ', err.message);
                if (callback) {
                    callback(err)
                }
                return;
            }
            Logger.log("DELETE resp=", result);
            if (callback) {
                callback(err, result)
            }
        });
    }

}